import {instance} from './AxiosConfig'
import {ResponseData} from "@/common/ResponseData";

// 请求公共参数设置
function requestCommon ( url:any, datas:any ) {
  var option = {
    isLoad: true, // 是否启动加载圈
    isLayer: false, // 是否启用默认加载弹框
    loadStyle: 3, // 加载圈样式
    timeout: 150, // 加载超时时间
    headers: {'Content-Type': 'application/json'}    //  'application/x-www-form-urlencoded'  application/json
  };

  option = Object.assign(option,datas);

  return option;
}

// 成功后的默认处理函数
function success(rep,option) {
  if ( option.isLayer ) {
    if ( rep.data.status ) {
      // @ts-ignore
      layer.msg(rep.data.message)
    } else {
      // @ts-ignore
      layer.msg(rep.data.message,{ shift: 6, time: 2000 })
    }
  }
}
// 失败后的默认处理函数
function fail(e) {
  // @ts-ignore
  layer.msg('服务端连接出错,错误原因:'+e.toString(),{ shift: 6, time: 2000 })
}
// 最后一定会执行的默认处理函数
function final() {

}
  // 封装get请求
  export let $get = function ( url, data={} ,datas={}):Promise<ResponseData> {
    var p = new Promise<ResponseData>(function(resolve, reject) {
      var option = requestCommon(url, datas);
      // @ts-ignore
      var indexUpload = layer.load(option.loadStyle, {time: option.timeout * 1000})
      instance.get(url, {params: data,headers:option.headers})
        .then(function (rep) {
          success(rep,option)
          // @ts-ignore
          resolve(rep.data)
        })
        .catch(function (e) {
          fail(e)
          reject(e)
        })
        .finally(function () {
          final()
          // @ts-ignore
          layer.close(indexUpload)
        });
    });
    return p
  }
  // 封装post请求
  export let $post = function  (url:any,data={}, datas={}):Promise<ResponseData>{
    var p = new Promise<ResponseData>(function(resolve, reject) {
      var option = requestCommon(url, datas);
      // @ts-ignore
      var indexUpload = layer.load(option.loadStyle, {time: option.timeout * 1000})

      var axiosPost = instance.post(url, data,{headers:option.headers}).then(function (rep) {
        success(rep,option)
        resolve(rep.data)
      }).catch(function (e) {
        fail(e)
        reject(e)
      }).finally(function () {
        final()
        // @ts-ignore
        layer.close(indexUpload)
      })
    })
    return p
  }
